package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.req.ResetUserPasswordRep;
import com.example.req.UserLoginRep;
import com.example.req.UserQueryReq;
import com.example.req.UserSaveRep;
import com.example.resp.UserLoginResp;
import com.example.service.UserService;
import com.example.utils.Result;
import com.example.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;


@RestController
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    SnowFlake snowFlake;

    @Autowired
    RedisTemplate redisTemplate;


    @GetMapping("/userList")
    public Result findUser(@Valid UserQueryReq req){
        return Result.success(userService.findUser(req));
    }

    @PostMapping("/user")
    public Result saveUser(@RequestBody @Valid UserSaveRep req) {

        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        userService.saveUser(req);
        return Result.success();
    }

    @PostMapping("/user/password")
    public Result resetUserPassword(@RequestBody @Valid ResetUserPasswordRep req) {

        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        userService.resetUserPassword(req);
        return Result.success();
    }

    @PostMapping("/user/login")
    public Result userLogin(@RequestBody @Valid UserLoginRep req) {

        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        UserLoginResp userLoginResp = userService.userLogin(req);

        Long token = snowFlake.nextId();
        System.out.println("生成的token："+token);
        userLoginResp.setToken(token.toString());
        redisTemplate.opsForValue().set(token.toString(), JSONObject.toJSONString(userLoginResp),3600*24,TimeUnit.SECONDS);

        return Result.success(userLoginResp);
    }
    
    @PostMapping("user/loginOut/{token}")
    public Result userLoginOut(@PathVariable("token") Long token){
        redisTemplate.delete(token);
        return Result.success();
    }
    

    @DeleteMapping("/user/{id}")
    public Result deleteUser(@PathVariable("id") Long id){
        userService.deleteUser(id);
        return Result.success();
    }

}
